package com.piston.app;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;

/**
 * 自定义布局，转轮视图
 * 
 * @description 使用SurfaceView实现
 * @author Dajige
 * 
 */
public class PistionAboutView extends SurfaceView implements
		SurfaceHolder.Callback {

	private SurfaceThread surfaceThread;
	// 画笔
	private Paint mPaint = new Paint();

	// 背景
	private Drawable mBackgroundDrawable;

	// 中心坐标
	private int mCenterX = 0, mCenterY = 0;

	// 坐标滚动偏移，用于动画左移坐标系
	private int mOffsetX = 0, mOffsetY = 0;

	// 多媒体播放器
	private MediaPlayer mediaPlayer;

	public PistionAboutView(Context context) {
		super(context);
		SurfaceHolder holder = getHolder();
		holder.addCallback(this);
		surfaceThread = new SurfaceThread(holder, context, new Handler() {
			@Override
			public void handleMessage(Message m) {
				Toast.makeText(getContext(), m.toString(), Toast.LENGTH_SHORT)
						.show();
			}
		});

		mPaint.setAntiAlias(true);// 消除锯齿。
		mPaint.setAlpha(0xff);// 不透明。

		mBackgroundDrawable = getResources().getDrawable(R.drawable.wood4);
		initializeMediaPlayer();
	}

	private void initializeMediaPlayer() {
//		mediaPlayer = MediaPlayer.create(this.getContext(),
//				R.raw.tinariwen_tenere_taqqim_tossam);
		mediaPlayer.setLooping(true);
		mediaPlayer.setVolume(.5f, .5f);
	}

	/**
	 * 更新变换坐标
	 */
	private void updateMatrix() {

		int width = getWidth();
		int height = getHeight();
		if (width * height == 0)
			return;
		mCenterX = width / 2;
		mCenterY = height / 2;
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		surfaceThread.setSurfaceSize(width, height);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		surfaceThread = new SurfaceThread(holder, getContext(), null);
		surfaceThread.setRunning(true);
		surfaceThread.start();

		if (mediaPlayer == null) {
			initializeMediaPlayer();
		}

		// 同时播放声音
		if (!mediaPlayer.isPlaying()) {
			mediaPlayer.start();
		} else {
			mediaPlayer.stop();
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		boolean retry = true;
		surfaceThread.setRunning(false);
		while (retry) {
			try {
				surfaceThread.join();
				retry = false;
			} catch (InterruptedException e) {
			}
		}

		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
			mediaPlayer = null;
		}
	}

	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();
	}

	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();
	}

	class SurfaceThread extends Thread {

		private boolean mIsRunning = true;
		private SurfaceHolder mSurfaceHolder;

		public SurfaceThread(SurfaceHolder surfaceHolder, Context context,
				Handler handler) {
			mSurfaceHolder = surfaceHolder;
		}

		public void setRunning(boolean b) {
			mIsRunning = b;
		}

		public boolean isRunning() {
			return mIsRunning;
		}

		/* Callback invoked when the surface dimensions change. */
		public void setSurfaceSize(int width, int height) {
			// synchronized to make sure these all change atomically
			synchronized (mSurfaceHolder) {

				// TODO don't forget to resize the background image
				// mBackgroundImage = mBackgroundImage.createScaledBitmap(
				// mBackgroundImage, width, height, true);
			}
			updateMatrix();
		}

		public void run() {
			while (mIsRunning) {
				Canvas c = null;
				try {
					c = mSurfaceHolder.lockCanvas(null);// 获取画布
					synchronized (mSurfaceHolder) {
						doDraw(c);
					}
				} finally {
					// do this in a finally so that if an exception is thrown
					// during the above, we don't leave the Surface in an
					// inconsistent state
					if (c != null) {
						mSurfaceHolder.unlockCanvasAndPost(c);// 解锁画布，提交画好的图像
					}
				}
			}
		}

		private void doDraw(Canvas canvas) {
			// // draw background
			// mBackgroundDrawable.setBounds(0, 0, canvas.getWidth(),
			// canvas.getHeight());
			// mBackgroundDrawable.draw(canvas);

			int lineOffset = 0;
			int lineOffsetStep = 40;
			String[] strings = new String[] { "Dajige", "Presents", "", "", "",
					"Music by Tinariwen", "", "", "",
					"TENERE TAQQIM TOSSAM",
					"Jealous Desert", "", "The desert is mine",
					"Tenere, my homeland,",
					"We come to you when the sun goes down",
					"Leaving a trail of blood across the sky",
					"Which the black night wipes out",
					"The desert is hot and its water hard to find",
					"Water is life and soul",
					"To all my brothers I say, the desert is jealous!", "",
					"O Tenere! A jealous desert!",
					"Why can‘t you see? You are a treasure",
					"I‘ve seen the world, I love you better",
					"Oh Tenere! You are the treasure of my soul.", "",
					"I cry out to God on High", "To bring my people together",
					"In unity" };

			canvas.drawColor(Color.BLACK);

			Drawable drawable = getResources().getDrawable(R.drawable.piston);

			mOffsetY = (mOffsetY + 1)
					% (getHeight() + drawable.getIntrinsicHeight() + strings.length
							* lineOffsetStep);
			drawable.setBounds(
					canvas.getWidth() / 2 - drawable.getIntrinsicWidth() / 2,
					(canvas.getHeight() - mOffsetY),
					canvas.getWidth() / 2 + drawable.getIntrinsicWidth() / 2,
					(canvas.getHeight() + drawable.getIntrinsicHeight() - mOffsetY));

			int alpha = Math.abs(drawable.getBounds().top - getBottom());
			if (alpha > 0xff)
				alpha = 0xff;
			if (Math.abs(drawable.getBounds().bottom - getTop()) < 0xff)
				alpha = Math.abs(drawable.getBounds().bottom - getTop());
			drawable.setAlpha(alpha);
			drawable.draw(canvas);

			mPaint.setAlpha(alpha);
			mPaint.setColor(Color.WHITE);
			mPaint.setTextScaleX(1);
			mPaint.setTextSize(lineOffsetStep);
			mPaint.setTextAlign(Align.CENTER);

			for (String s : strings) {
				lineOffset += lineOffsetStep;
				canvas.drawText(s, canvas.getWidth() / 2, (canvas.getHeight()
						+ drawable.getIntrinsicHeight() - mOffsetY)
						+ lineOffset, mPaint);
			}

			drawScratch(canvas);
		}

		private void drawScratch(Canvas canvas) {

			mPaint.setAlpha(0xff);

			if (Math.random() > .98) {

				float startX = (float) Math.random() * canvas.getWidth();
				float startY = (float) Math.random() * canvas.getHeight();
				float stopX = (float) Math.random() * canvas.getWidth();
				float stopY = (float) Math.random() * canvas.getHeight();
				mPaint.setStrokeWidth((float) (Math.random() * 10));
				// mPaint.setColor(Color.argb((int) (Math.random() * 0xff),
				// (int) (Math.random() * 0xff),
				// (int) (Math.random() * 0xff),
				// (int) (Math.random() * 0xff)));
				canvas.drawLine(startX, startY, startX, stopY, mPaint);
			}
			if (Math.random() > .98) {

				float startX = (float) Math.random() * canvas.getWidth();
				float startY = (float) Math.random() * canvas.getHeight();
				float stopX = (float) Math.random() * canvas.getWidth();
				float stopY = (float) Math.random() * canvas.getHeight();
				mPaint.setTextSize((float) (Math.random() * 80));
				mPaint.setColor(Color.argb((int) (Math.random() * 0xff),
						(int) (Math.random() * 0xff),
						(int) (Math.random() * 0xff),
						(int) (Math.random() * 0xff)));
				int index = (int) (Math.random() * 10);
				canvas.drawText(index + "", startX, startY, mPaint);
			}
			if (Math.random() > .98) {

				float startX = (float) Math.random() * canvas.getWidth();
				float startY = (float) Math.random() * canvas.getHeight();
				float stopX = (float) Math.random() * canvas.getWidth();
				float stopY = (float) Math.random() * canvas.getHeight();
				mPaint.setTextSize((float) (Math.random() * 80));
				mPaint.setColor(Color.argb((int) (Math.random() * 0xff),
						(int) (Math.random() * 0xff),
						(int) (Math.random() * 0xff),
						(int) (Math.random() * 0xff)));
				String[] stars = new String[] { "★", "♠", "♥", "♦", "♣", "◆",
						"■" };
				int index = Math.min((int) (Math.random() * stars.length),
						stars.length - 1);
				canvas.drawText(stars[index], startX, startY, mPaint);
			}

		}
	}
}
